package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.mapper.ChatGroupMemberSettingMapper;
import com.zenithmind.chat.pojo.entity.ChatGroupMemberSetting;
import com.zenithmind.chat.pojo.dto.ChatGroupMemberSettingDTO;
import com.zenithmind.chat.pojo.vo.ChatGroupMemberSettingVO;
import com.zenithmind.chat.service.ChatGroupMemberSettingService;
import com.zenithmind.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 群组成员设置服务实现类 - 遵循单一职责原则
 * 只负责群组成员设置的业务逻辑处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatGroupMemberSettingServiceImpl extends ServiceImpl<ChatGroupMemberSettingMapper, ChatGroupMemberSetting> 
        implements ChatGroupMemberSettingService {

    @Override
    public ChatGroupMemberSettingVO getMemberSetting(String groupId, String userId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            throw new BusinessException("群组ID不能为空");
        }
        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("用户ID不能为空");
        }
        
        ChatGroupMemberSetting setting = baseMapper.selectByGroupIdAndUserId(groupId, userId);
        if (setting == null) {
            // 如果没有设置，创建默认设置
            createDefaultSetting(groupId, userId, "system");
            setting = baseMapper.selectByGroupIdAndUserId(groupId, userId);
        }
        
        return convertToVO(setting);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMemberSetting(ChatGroupMemberSettingDTO dto, String operatorId) {
        if (!dto.isValid()) {
            throw new BusinessException("成员设置信息不完整");
        }
        
        ChatGroupMemberSetting setting = baseMapper.selectByGroupIdAndUserId(dto.getGroupId(), dto.getUserId());
        if (setting == null) {
            throw new BusinessException("成员设置不存在");
        }
        
        // 更新设置信息
        updateSettingFromDTO(setting, dto);
        setting.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(setting);
        
        if (result) {
            log.info("更新成员设置成功，群组ID: {}, 用户ID: {}, 操作人: {}", 
                    dto.getGroupId(), dto.getUserId(), operatorId);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createDefaultSetting(String groupId, String userId, String operatorId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            throw new BusinessException("群组ID不能为空");
        }
        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 检查是否已存在设置
        if (checkSettingExists(groupId, userId)) {
            ChatGroupMemberSetting existing = baseMapper.selectByGroupIdAndUserId(groupId, userId);
            return existing.getId();
        }
        
        ChatGroupMemberSetting setting = createDefaultSettingEntity(groupId, userId);
        save(setting);
        
        log.info("创建默认成员设置成功，群组ID: {}, 用户ID: {}, 操作人: {}", 
                groupId, userId, operatorId);
        
        return setting.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteMemberSetting(String groupId, String userId, String operatorId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            throw new BusinessException("群组ID不能为空");
        }
        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("用户ID不能为空");
        }
        
        ChatGroupMemberSetting setting = baseMapper.selectByGroupIdAndUserId(groupId, userId);
        if (setting == null) {
            throw new BusinessException("成员设置不存在");
        }
        
        // 逻辑删除
        setting.setIsDeleted(1);
        setting.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(setting);
        
        if (result) {
            log.info("删除成员设置成功，群组ID: {}, 用户ID: {}, 操作人: {}", 
                    groupId, userId, operatorId);
        }
        
        return result;
    }

    @Override
    public List<ChatGroupMemberSettingVO> getGroupMemberSettings(String groupId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            throw new BusinessException("群组ID不能为空");
        }
        
        List<ChatGroupMemberSetting> settings = baseMapper.selectByGroupId(groupId);
        return settings.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public List<ChatGroupMemberSettingVO> getUserGroupSettings(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("用户ID不能为空");
        }
        
        List<ChatGroupMemberSetting> settings = baseMapper.selectByUserId(userId);
        return settings.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMemberNickname(String groupId, String userId, String nickname, String operatorId) {
        int result = baseMapper.updateNickname(groupId, userId, nickname);
        
        if (result > 0) {
            log.info("更新成员昵称成功，群组ID: {}, 用户ID: {}, 昵称: {}, 操作人: {}", 
                    groupId, userId, nickname, operatorId);
        }
        
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTopStatus(String groupId, String userId, Boolean isTop, String operatorId) {
        int result = baseMapper.updateTopStatus(groupId, userId, isTop);
        
        if (result > 0) {
            log.info("更新置顶状态成功，群组ID: {}, 用户ID: {}, 置顶: {}, 操作人: {}", 
                    groupId, userId, isTop, operatorId);
        }
        
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMuteStatus(String groupId, String userId, Boolean isMuted, String operatorId) {
        int result = baseMapper.updateMuteStatus(groupId, userId, isMuted);
        
        if (result > 0) {
            log.info("更新免打扰状态成功，群组ID: {}, 用户ID: {}, 免打扰: {}, 操作人: {}", 
                    groupId, userId, isMuted, operatorId);
        }
        
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMessageNotification(String groupId, String userId, Integer messageNotification, String operatorId) {
        int result = baseMapper.updateMessageNotification(groupId, userId, messageNotification);
        
        if (result > 0) {
            log.info("更新消息提醒设置成功，群组ID: {}, 用户ID: {}, 提醒设置: {}, 操作人: {}", 
                    groupId, userId, messageNotification, operatorId);
        }
        
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateShowMemberNickname(String groupId, String userId, Boolean showMemberNickname, String operatorId) {
        int result = baseMapper.updateShowMemberNickname(groupId, userId, showMemberNickname);
        
        if (result > 0) {
            log.info("更新显示成员昵称设置成功，群组ID: {}, 用户ID: {}, 显示昵称: {}, 操作人: {}", 
                    groupId, userId, showMemberNickname, operatorId);
        }
        
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSaveToContacts(String groupId, String userId, Boolean saveToContacts, String operatorId) {
        int result = baseMapper.updateSaveToContacts(groupId, userId, saveToContacts);
        
        if (result > 0) {
            log.info("更新保存到通讯录设置成功，群组ID: {}, 用户ID: {}, 保存到通讯录: {}, 操作人: {}", 
                    groupId, userId, saveToContacts, operatorId);
        }
        
        return result > 0;
    }

    @Override
    public List<ChatGroupMemberSettingVO> getTopGroups(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("用户ID不能为空");
        }
        
        List<ChatGroupMemberSetting> settings = baseMapper.selectTopGroupsByUserId(userId);
        return settings.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public List<ChatGroupMemberSettingVO> getMutedGroups(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("用户ID不能为空");
        }
        
        List<ChatGroupMemberSetting> settings = baseMapper.selectMutedGroupsByUserId(userId);
        return settings.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public List<ChatGroupMemberSettingVO> getTopMembers(String groupId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            throw new BusinessException("群组ID不能为空");
        }
        
        List<ChatGroupMemberSetting> settings = baseMapper.selectTopMembersByGroupId(groupId);
        return settings.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public List<ChatGroupMemberSettingVO> getMutedMembers(String groupId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            throw new BusinessException("群组ID不能为空");
        }
        
        List<ChatGroupMemberSetting> settings = baseMapper.selectMutedMembersByGroupId(groupId);
        return settings.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public Boolean checkSettingExists(String groupId, String userId) {
        if (groupId == null || groupId.trim().isEmpty() || userId == null || userId.trim().isEmpty()) {
            return false;
        }
        
        return baseMapper.checkSettingExists(groupId, userId) > 0;
    }

    @Override
    public Integer countTopGroups(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            return 0;
        }
        
        return baseMapper.countTopGroupsByUserId(userId);
    }

    @Override
    public Integer countMutedGroups(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            return 0;
        }
        
        return baseMapper.countMutedGroupsByUserId(userId);
    }

    @Override
    public Integer countTopMembers(String groupId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            return 0;
        }
        
        return baseMapper.countTopMembersByGroupId(groupId);
    }

    @Override
    public Integer countMutedMembers(String groupId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            return 0;
        }
        
        return baseMapper.countMutedMembersByGroupId(groupId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer batchDeleteByGroupId(String groupId, String operatorId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            throw new BusinessException("群组ID不能为空");
        }
        
        int deletedCount = baseMapper.batchDeleteByGroupId(groupId);
        
        if (deletedCount > 0) {
            log.info("批量删除群组成员设置成功，群组ID: {}, 删除数量: {}, 操作人: {}", 
                    groupId, deletedCount, operatorId);
        }
        
        return deletedCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer batchDeleteByUserId(String userId, String operatorId) {
        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("用户ID不能为空");
        }
        
        int deletedCount = baseMapper.batchDeleteByUserId(userId);
        
        if (deletedCount > 0) {
            log.info("批量删除用户群组设置成功，用户ID: {}, 删除数量: {}, 操作人: {}", 
                    userId, deletedCount, operatorId);
        }
        
        return deletedCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchUpdateMemberSettings(String groupId, List<String> userIds, ChatGroupMemberSettingDTO dto, String operatorId) {
        if (groupId == null || groupId.trim().isEmpty()) {
            throw new BusinessException("群组ID不能为空");
        }
        if (userIds == null || userIds.isEmpty()) {
            throw new BusinessException("用户ID列表不能为空");
        }
        
        for (String userId : userIds) {
            dto.setGroupId(groupId);
            dto.setUserId(userId);
            updateMemberSetting(dto, operatorId);
        }
        
        log.info("批量更新成员设置成功，群组ID: {}, 用户数量: {}, 操作人: {}", 
                groupId, userIds.size(), operatorId);
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean copyMemberSetting(String sourceGroupId, String sourceUserId, String targetGroupId, String targetUserId, String operatorId) {
        ChatGroupMemberSettingVO sourceSetting = getMemberSetting(sourceGroupId, sourceUserId);
        if (sourceSetting == null) {
            throw new BusinessException("源成员设置不存在");
        }
        
        // 创建目标设置
        ChatGroupMemberSetting targetSetting = createDefaultSettingEntity(targetGroupId, targetUserId);
        
        // 复制设置
        targetSetting.setNickname(sourceSetting.getNickname());
        targetSetting.setIsTop(sourceSetting.getIsTop());
        targetSetting.setIsMuted(sourceSetting.getIsMuted());
        targetSetting.setMessageNotification(sourceSetting.getMessageNotification());
        targetSetting.setShowMemberNickname(sourceSetting.getShowMemberNickname());
        targetSetting.setSaveToContacts(sourceSetting.getSaveToContacts());
        
        save(targetSetting);
        
        log.info("复制成员设置成功，源: {}:{}, 目标: {}:{}, 操作人: {}", 
                sourceGroupId, sourceUserId, targetGroupId, targetUserId, operatorId);
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean resetToDefault(String groupId, String userId, String operatorId) {
        // 删除现有设置
        deleteMemberSetting(groupId, userId, operatorId);
        
        // 创建默认设置
        createDefaultSetting(groupId, userId, operatorId);
        
        log.info("重置成员设置为默认值成功，群组ID: {}, 用户ID: {}, 操作人: {}", 
                groupId, userId, operatorId);
        
        return true;
    }

    @Override
    public String exportMemberSettings(String groupId, String operatorId) {
        // TODO: 实现成员设置导出逻辑
        return "";
    }

    @Override
    public Boolean importMemberSettings(String groupId, String filePath, String operatorId) {
        // TODO: 实现成员设置导入逻辑
        return false;
    }

    @Override
    public Object getMemberSettingStatistics(String groupId) {
        // TODO: 实现成员设置统计逻辑
        return new Object();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean syncMemberSetting(String groupId, String userId, String operatorId) {
        // TODO: 实现成员设置同步逻辑
        return true;
    }

    /**
     * 创建默认设置实体
     */
    private ChatGroupMemberSetting createDefaultSettingEntity(String groupId, String userId) {
        ChatGroupMemberSetting setting = new ChatGroupMemberSetting();
        setting.setGroupId(groupId);
        setting.setUserId(userId);
        setting.setNickname("");
        setting.setIsTop(false);
        setting.setIsMuted(false);
        setting.setMessageNotification(1); // 默认接收所有消息
        setting.setShowMemberNickname(true);
        setting.setSaveToContacts(false);
        setting.setCreateTime(LocalDateTime.now());
        setting.setUpdateTime(LocalDateTime.now());
        return setting;
    }

    /**
     * 从DTO更新设置
     */
    private void updateSettingFromDTO(ChatGroupMemberSetting setting, ChatGroupMemberSettingDTO dto) {
        if (dto.getNickname() != null) {
            setting.setNickname(dto.getNickname());
        }
        if (dto.getIsTop() != null) {
            setting.setIsTop(dto.getIsTop());
        }
        if (dto.getIsMuted() != null) {
            setting.setIsMuted(dto.getIsMuted());
        }
        if (dto.getMessageNotification() != null) {
            setting.setMessageNotification(dto.getMessageNotification());
        }
        if (dto.getShowMemberNickname() != null) {
            setting.setShowMemberNickname(dto.getShowMemberNickname());
        }
        if (dto.getSaveToContacts() != null) {
            setting.setSaveToContacts(dto.getSaveToContacts());
        }
    }

    /**
     * 转换为VO
     */
    private ChatGroupMemberSettingVO convertToVO(ChatGroupMemberSetting setting) {
        ChatGroupMemberSettingVO vo = new ChatGroupMemberSettingVO();
        vo.setId(setting.getId());
        vo.setGroupId(setting.getGroupId());
        vo.setUserId(setting.getUserId());
        vo.setNickname(setting.getNickname());
        vo.setIsTop(setting.getIsTop());
        vo.setIsMuted(setting.getIsMuted());
        vo.setMessageNotification(setting.getMessageNotification());
        vo.setShowMemberNickname(setting.getShowMemberNickname());
        vo.setSaveToContacts(setting.getSaveToContacts());
        vo.setCreateTime(setting.getCreateTime());
        vo.setUpdateTime(setting.getUpdateTime());
        return vo;
    }
}
